package com.xuecheng.base.utils;

import org.springframework.beans.BeanUtils;
import java.util.function.Function;
import java.util.function.Supplier;

public class BeanCopyUtil {

    /**
     * 对象属性拷贝（提供目标对象实例）
     * 示例：XcUserExt ext = BeanCopyUtil.copyProperties(user, XcUserExt::new);
     *
     * @param source  源对象
     * @param targetSupplier  目标对象构造函数
     * @return 拷贝后的目标对象
     */
    public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier) {
        T target = targetSupplier.get();
        BeanUtils.copyProperties(source, target);
        return target;
    }

    /**
     * 对象属性拷贝（支持自定义转换）
     * 示例：XcUserDto dto = BeanCopyUtil.copyProperties(user, XcUserExt::new, ext -> {
     *         XcUserDto dto = new XcUserDto();
     *         // 自定义字段映射
     *         dto.setDisplayName(ext.getFullName());
     *         return dto;
     *     });
     *
     * @param source  源对象
     * @param intermediateSupplier  中间对象构造函数
     * @param mapper  自定义转换函数
     * @return 转换后的最终对象
     */
    public static <S, I, R> R copyProperties(S source, Supplier<I> intermediateSupplier, Function<I, R> mapper) {
        I intermediate = copyProperties(source, intermediateSupplier);
        return mapper.apply(intermediate);
    }
}